/*
 * @Author: pardon110
 * @Date: 2024-03-27 14:22:29
 * @LastEditors: pardon110@qq.com
 * @LastEditTime: 2024-03-27 14:36:56
 * @FilePath: \days7\orm\reflect-schema\session\hooks.go
 * @Description:  通过反射获取结构体绑定的钩子，并调用
 */
package session

import (
	"reflect"

	"days7.test/orm/log"
)

const (
	BeforeQuery  = "BeforeQuery"
	AfterQuery   = "AfterQuery"
	BeforeUpdate = "BeforeUpdate"
	AfterUpdate  = "AfterUpdate"
	BeforeDelete = "BeforeDelete"
	AfterDelete  = "AfterDelete"
	BeforeInsert = "BeforeInsert"
	AfterInsert  = "AfterInsert"
)

// 通过反射来实现的，s.RefTable().Model 或 value 即当前会话正在操作的对象
func (s *Session) CallMethod(method string, value interface{}) {
	fm := reflect.ValueOf(s.RefTable().Model).MethodByName(method)
	if value != nil {
		fm = reflect.ValueOf(value).MethodByName(method)
	}

	// 将 s *Session 作为入参调用。每一个钩子的入参类型均是 *Session
	param := []reflect.Value{reflect.ValueOf(s)}
	if fm.IsValid() {
		if v := fm.Call(param); len(v) > 0 {
			if err, ok := v[0].Interface().(error); ok {
				log.Error(err)
			}
		}
	}

}
